package com.manong.bookstore.user.service.impl;

import com.alibaba.nacos.client.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manong.common.utils.PageUtils;
import com.manong.common.utils.Query;

import com.manong.bookstore.user.dao.UserDao;
import com.manong.bookstore.user.entity.UserEntity;
import com.manong.bookstore.user.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Value("${iconBasePath}")
    private String iconBasePath;
    @Value("${defaultUserIcon}")
    private String defaultUserIcon;

//    @Override
//    public PageUtils queryPage(Map<String, Object> params) {
//        IPage<UserEntity> page = this.page(
//                new Query<UserEntity>().getPage(params),
//                new QueryWrapper<UserEntity>()
//        );
//
//        return new PageUtils(page);
//    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //1、获取key
        String key = (String) params.get("key");
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();

        if(!StringUtils.isEmpty(key)){
            queryWrapper.eq("user_id",key)
                    .or().eq("points",key)
                    .or().eq("user_type",key)
                    .or().like("user_name",key)
                    .or().like("phone_number",key)
                    .or().like("email",key);
        }

        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }
    
    @Override
    public Integer register(UserEntity user) {
        List<UserEntity> idList = baseMapper.selectList(new QueryWrapper<UserEntity>().select("user_id").orderByDesc("user_id"));
        int userId = 1;
        
//        for(UserEntity userEntity : idList) {
//            System.out.println(userEntity);
//        }

        // 获取用户id（查表找最大的一个然后+1）
        if(idList.size() > 0)
            userId = idList.get(0).getUserId() + 1;

        // 检查用户名是否与 用户名字段 和 手机号字段 重复
        // 因为登录时可以使用 用户名 和 手机号，需要保证 用户名+手机号 合并之后都是唯一的
        if(baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("user_name", user.getUserName())) > 0) {
            return -1;
        }
        else if(baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("phone_number", user.getUserName())) > 0) {
            return -1;
        }
    
        if(baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("phone_number", user.getPhoneNumber())) > 0) {
            return -2;
        }
        else if(baseMapper.selectCount(new QueryWrapper<UserEntity>().eq("user_name", user.getPhoneNumber())) > 0) {
            return -2;
        }
        
        user.setUserId(userId);
        user.setPoints(new BigDecimal(0));
        user.setUserType(1);
        user.setUserIcon(iconBasePath + defaultUserIcon);// TODO 设置用户初始图片路径
        
        baseMapper.insert(user);
        
        return userId;
    }

    @Override
    public UserEntity login(String ID, String password, String checkColumn) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<UserEntity>().eq(checkColumn, ID);
        List<UserEntity> result = baseMapper.selectList(wrapper);

        if (result.size() == 1) {
            UserEntity user = result.get(0);

            if (password.toString().equals(user.getPassword())) {
                return user;
            }
            else
                return null;
        }

        return null;
    }

    @Override
    public boolean updateInfo(String userId, String name, String value) {
        UserEntity user = baseMapper.selectById(userId);

        if(user != null) {
            switch (name) {
                case "email":
                    user.setEmail(value);
                    break;
                case "userIcon":
                    user.setUserIcon(value);
                    break;
                case "password":
                    user.setPassword(value);
                    break;
            }

            baseMapper.updateById(user);

            return true;
        }

        return false;
    }

    @Override
    public void addPoint(Integer userId, BigDecimal point) {
        UserEntity user = baseMapper.selectById(userId);
        
        user.setPoints(user.getPoints().add(point));
        
        baseMapper.updateById(user);
    }
    
    @Override
    public void delPoint(Integer userId, BigDecimal point) {
        UserEntity user = baseMapper.selectById(userId);
        
        user.setPoints(user.getPoints().subtract(point));
        
        baseMapper.updateById(user);
    }
    
}